package com.duoec.doc.helper;

import com.duoec.doc.entity.MockConfigItem;
import com.duoec.doc.service.IBaseTypeMocker;
import com.duoec.doc.service.IMocker;
import com.duoec.doc.service.impl.mock.operator.MockOperator;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author xuwenzhen
 * @date 2020/2/1
 */
public class MockHelper {
    private static final Logger logger = LoggerFactory.getLogger(MockHelper.class);
    private static final int BASE_TYPE_MOCKER_PLUS = 1000;
    public static Map<Integer, IMocker> MOCKER_MAP = Maps.newHashMap();
    public static Map<String, MockOperator> MOCK_OPERATOR_MAP = Maps.newHashMap();

    /**
     * 判断某个mock配置是否有效
     *
     * @param item mock配置
     * @return mock配置是否有效
     */
    public static boolean available(MockConfigItem item) {
        Boolean available = item.getAvailable();
        return available == null || available;
    }

    public static void registryMocker(IMocker mocker) {
        if (mocker instanceof IBaseTypeMocker) {
            //基础类型
            MOCKER_MAP.put(mocker.getMockType() + BASE_TYPE_MOCKER_PLUS, mocker);
        } else {
            MOCKER_MAP.put(mocker.getMockType(), mocker);
        }
    }

    public static IMocker getMocker(MockConfigItem item) {
        //类型：0=基本类型 1=枚举 2=pojo 3=collection 4=map 5=数组
        Integer type = item.getType();
        String entityName = item.getEntityName();
        IMocker mocker;
        if (type == 0 || type == 1) {
            // 基本类型或枚举类型
            mocker = MOCKER_MAP.get(item.getBaseType() + BASE_TYPE_MOCKER_PLUS);
            if (mocker == null) {
                logger.warn("未实现mocker: {}.type={}, {}.baseType={}", entityName, type, entityName, item.getBaseType());
                return null;
            }
            return mocker;
        } else {
            mocker = MOCKER_MAP.get(type);
            if (mocker == null) {
                logger.warn("未实现mocker: {}.type={}", entityName, item.getType());
                return null;
            }
            return mocker;
        }
    }

    public static void registryOperator(MockOperator mockOperator) {
        MOCK_OPERATOR_MAP.put(mockOperator.getOperator(), mockOperator);
    }

    public static MockOperator getOperator(String mockOperator) {
        return MOCK_OPERATOR_MAP.get(mockOperator);
    }
}
